package org.sensornet2010.core;

import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;

public class Storage {
	
	/*
	 * Persistent information
	 * 
	 * Configuration: key=value, key=value,
	 * Internal state: key=value, key=value
	 * Sensor data: id = [byte]
	 * 
	 */
	
	public String getDebugInfo(){
		long freeMemory = Runtime.getRuntime().freeMemory();
		String info = "Free memory:" + freeMemory + "\n";
		String[] names = RecordStore.listRecordStores();
		for (int i = 0; i < names.length; i++) {
			String name = names[i];
			info+=name;
			try {
				RecordStore rs = RecordStore.openRecordStore(name, false);
				info += "=" + new String(getFirstRecord(rs)) +"\n";
				info += ":"+ rs.getNumRecords();
				info += ":" + rs.getSize();
				info += ":\n" + rs.getSizeAvailable() + "\n";
				rs.closeRecordStore();
			} catch (Exception e) {
				info+= "ERROR:" + e.getMessage() +":\n";
			}
		}
		return info;
		
	}
	
	public String getValue(String key){
		byte[] value = this.getByteArray(key);
		if (value == null) return null;
		else return new String();
	}
	public void setValue(String key, String value){
		this.setByteArray(key, value.getBytes());
	}
	
	
	private byte[] getFirstRecord(RecordStore rs) throws RecordStoreException{
		byte[] value = null;
		RecordEnumeration re = rs.enumerateRecords(null, null, false);
		while (re.hasNextElement()) {
			value = re.nextRecord();
		}
/*		byte[] value = new byte[0];
		if (rs.getNumRecords()>1){
			int id = rs.enumerateRecords(null, null, false).nextRecordId();
			value = rs.getRecord(id);
		}
*/		
		return value;
	}
	
	public byte[] getByteArray(String key){
		RecordStore rs;
		try {
			rs = RecordStore.openRecordStore(key, true);
			byte[] value = this.getFirstRecord(rs);
			rs.closeRecordStore();
			return value;
		} catch (Exception e){
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
	}
	public void setByteArray(String key, byte[] value){
		RecordStore rs;
		try {
			rs = RecordStore.openRecordStore(key, true);
			if (rs.getNumRecords()>1){
				int id = rs.enumerateRecords(null, null, false).nextRecordId();
				rs.setRecord(id, value, 0, value.length);
			} else 
				rs.addRecord(value, 0, value.length);
			rs.closeRecordStore();
		} catch (Exception e){
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
	}
	
	
	
	
	
	
	
	
	
	

}
